<template>
    <div class="step1-basic">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="110px"
        class="form-area"
        size="large"
      >
        <!-- 任务基本信息 -->
        <el-card shadow="never" class="mb24">
          <template #header>任务基本信息</template>
          <el-form-item label="任务标题" prop="taskTitle">
            <el-input
              v-model="form.taskTitle"
              maxlength="30"
              show-word-limit
              placeholder="请输入任务标题"
              @input="autoSubtitle; updateParent"
            />
          </el-form-item>
          <el-form-item label="副标题">
            <el-input v-model="form.taskSubtitle" placeholder="自动生成或手动编辑" @input="updateParent" />
          </el-form-item>
          <el-form-item label="任务描述" prop="taskDescription">
            <el-input
              v-model="form.taskDescription"
              type="textarea"
              :rows="4"
              placeholder="请输入任务描述"
              @input="updateParent"
            />
          </el-form-item>
          <el-form-item label="任务类型" prop="taskType">
            <el-select v-model="form.taskType" placeholder="请选择任务类型" @change="updateParent">
              <el-option label="日常" value="DAILY" />
              <el-option label="限时" value="TIME_LIMITED" />
            </el-select>
          </el-form-item>
          <el-form-item label="任务领取类型" prop="claimType">
            <el-radio-group v-model="form.claimType" @change="updateParent">
              <el-radio :label="'AUTO'">自动领取</el-radio>
              <el-radio :label="'MANUAL'">手动领取</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="任务图标/封面">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :on-change="handleAvatarChange"
            >
              <img v-if="form.taskCoverUrl" :src="form.taskCoverUrl" class="avatar" />
              <el-icon v-else><Plus /></el-icon>
            </el-upload>
            <el-button @click="showIconLib = true" type="link">从图标库选择</el-button>
          </el-form-item>
        </el-card>
  
        <!-- 时间设置 -->
        <el-card shadow="never" class="mb24">
          <template #header>时间设置</template>
          <el-form-item label="任务周期" prop="cycleType">
            <el-radio-group v-model="form.cycleType" @change="updateParent">
              <el-radio value="once">一次性</el-radio>
              <el-radio value="daily">每日</el-radio>
              <el-radio value="weekly">每周</el-radio>
              <el-radio value="monthly">每月</el-radio>
              <el-radio value="custom">自定义</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime" v-if="form.cycleType === 'custom'">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              placeholder="选择开始时间"
              style="width: 100%;"
              @change="updateParent"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime" v-if="form.cycleType === 'custom'">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="选择结束时间"
              style="width: 100%;"
              @change="updateParent"
            />
          </el-form-item>
        </el-card>
  
        <!-- 可见性设置 -->
        <el-card shadow="never" class="mb24">
          <template #header>可见性设置</template>
          <el-form-item label="面向用户群体" prop="userGroupType">
            <el-radio-group v-model="form.userGroupType" @change="updateParent">
              <el-radio value="all">全部用户</el-radio>
              <el-radio value="new">新用户</el-radio>
              <el-radio value="active">活跃用户</el-radio>
              <el-radio value="custom">自定义用户组</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="显示位置" prop="showPos">
            <el-checkbox-group v-model="form.showPos" @change="updateParent">
              <el-checkbox label="个人中心页" />
              <el-checkbox label="首页" />
              <el-checkbox label="发现页" />
              <el-checkbox label="任务广场" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-slider v-model="form.priority" :min="1" :max="100" show-input @change="updateParent" />
          </el-form-item>
        </el-card>
  
        <!-- 任务限制 -->
        <el-card shadow="never" class="mb24">
          <template #header>任务限制</template>
          <el-form-item label="参与次数限制" prop="maxParticipate">
            <el-input-number v-model="form.maxParticipate" :min="0" @change="updateParent" />
            <span class="el-form-item__extra">0 表示无限制</span>
          </el-form-item>
        </el-card>
  
        <!-- 高级设置 -->
        <!-- <el-card shadow="never"> ... </el-card> -->
      </el-form>
  
      <!-- 预览区域 -->
      <div class="preview-area">
        <h3>预览区域</h3>
        <el-card>
          <div>
            <strong>{{ form.taskTitle }}</strong>
            <div style="color: #888;">{{ form.taskSubtitle }}</div>
            <div style="margin: 8px 0;">{{ form.taskDescription }}</div>
            <div v-if="form.taskCoverUrl">
              <img :src="form.taskCoverUrl" style="max-width: 100px;max-height: 100px;" />
            </div>
            <div>类型：{{ typeLabel(form.taskType) }}</div>
            <div>周期：{{ cycleLabel(form.cycleType) }}</div>
            <div>优先级：{{ form.priority }}</div>
          </div>
        </el-card>
      </div>
  
      <!-- 图标库弹窗 -->
      <el-dialog v-model="showIconLib" title="选择图标" width="400px">
        <div style="display: flex; flex-wrap: wrap; gap: 12px;">
          <img
            v-for="icon in iconLib"
            :key="icon"
            :src="icon"
            style="width: 48px; height: 48px; cursor: pointer; border-radius: 8px;"
            @click="selectIcon(icon)"
          />
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, watch, onMounted } from 'vue'
  import { Plus } from '@element-plus/icons-vue'
  import dayjs from 'dayjs'
  
  const form = reactive({
    taskTitle: '',
    taskSubtitle: '',
    taskDescription: '',
    taskCoverUrl: '',
    cycleType: '',
    taskType: '',
    startTime: '',
    endTime: '',
    maxParticipate: 0,
    userGroupType: '',
    showPos: [],
    priority: '',
    claimType: 'AUTO'
  })
  
  onMounted(() => {
    const cache = localStorage.getItem('step1Data')
    if (cache) Object.assign(form, JSON.parse(cache))
  })
  
  watch(form, (val) => {
    const data = { ...val }
    if (data.startTime) data.startTime = dayjs(data.startTime).format('YYYY-MM-DD HH:mm:ss')
    if (data.endTime) data.endTime = dayjs(data.endTime).format('YYYY-MM-DD HH:mm:ss')
    localStorage.setItem('step1Data', JSON.stringify(data))
  }, { deep: true })
  
  function saveToLocalStorage() {
    const data = { ...form }
    if (data.startTime) data.startTime = dayjs(data.startTime).format('YYYY-MM-DD HH:mm:ss')
    if (data.endTime) data.endTime = dayjs(data.endTime).format('YYYY-MM-DD HH:mm:ss')
    localStorage.setItem('step1Data', JSON.stringify(data))
  }
  
  const rules = {
    taskTitle: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
    taskType: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
  }
  
  function autoSubtitle() {
    if (!form.taskSubtitle) {
      form.taskSubtitle = form.taskTitle ? `快来参与"${form.taskTitle}"任务吧！` : ''
    }
  }
  
  function handleAvatarChange(file) {
    const reader = new FileReader()
    reader.onload = e => {
      form.taskCoverUrl = e.target.result
    }
    reader.readAsDataURL(file.raw)
  }
  
  const showIconLib = ref(false)
  const iconLib = [
    'https://img.icons8.com/color/48/000000/trophy.png',
    'https://img.icons8.com/color/48/000000/medal.png',
    'https://img.icons8.com/color/48/000000/star.png',
    'https://img.icons8.com/color/48/000000/rocket.png'
  ]
  function selectIcon(icon) {
    form.taskCoverUrl = icon
    showIconLib.value = false
  }
  
  const regionOptions = [
    {
      value: 'beijing',
      label: '北京',
      children: [{ value: 'dongcheng', label: '东城区' }, { value: 'xicheng', label: '西城区' }]
    },
    {
      value: 'shanghai',
      label: '上海',
      children: [{ value: 'huangpu', label: '黄浦区' }, { value: 'xuhui', label: '徐汇区' }]
    }
  ]
  
  function typeLabel(type) {
    return { daily: '日常', timed: '限时', achievement: '成就' }[type] || ''
  }
  function cycleLabel(cycle) {
    return { once: '一次性', daily: '每日', weekly: '每周', monthly: '每月', custom: '自定义' }[cycle] || ''
  }
  
  function updateParent() {
    // No need to emit, as we're directly updating localStorage
  }
  
  defineExpose({
    saveToLocalStorage
  })
  </script>
  
  <style scoped>
  .step1-basic {
    display: flex;
    gap: 24px;
  }
  .form-area {
    flex: 2;
    background: #fff;
    padding: 24px;
    border-radius: 8px;
    min-width: 480px;
  }
  .preview-area {
    flex: 1;
    background: #f5f7fa;
    padding: 24px;
    border-radius: 8px;
    min-width: 320px;
  }
  .mb24 {
    margin-bottom: 24px;
  }
  .avatar-uploader {
    display: inline-block;
    margin-right: 12px;
  }
  .avatar {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    object-fit: cover;
    border: 1px solid #eee;
  }
  </style>